package com.jason.serivce.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.jason.bean.Resource;
import com.jason.bean.Role;
import com.jason.bean.vo.Menu;
import com.jason.dao.ResourceDao;
import com.jason.dao.RoleDao;
import com.jason.service.ResourceService;

@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {
	@javax.annotation.Resource
	private RoleDao roleDao;
	@javax.annotation.Resource
	private ResourceDao resourceDao;

	@Override
	public List<Menu> findByRoles(List<Role> roles) {
		List<Integer> ids = new ArrayList<>();
		roles.forEach(role -> {
			ids.add(role.getId());
		});
		List<Role> list = roleDao.findAllById(ids);
		// 整理所有的资源,方便使用资源ID获取资源对象
		Map<Integer, Menu> resourceIds = new HashMap<>();
		for (Role role : list) {
			List<Resource> resources = resourceDao.findByRoleId(role.getId());
			for (Resource resource : resources) {
				resourceIds.put(resource.getId(), Menu.toResourceForMenu(resource));
			}
		}

		List<Menu> menuMaps = new ArrayList<>();
		for (Menu resource : resourceIds.values()) {
			if (resource.getPid() == -1) {
				menuMaps.add(resource);
			} else {
				findMenu(resource, resourceIds);
			}
		}

		return menuMaps;
	}

	private void findMenu(Menu menu, Map<Integer, Menu> resourceIds) {
		if (menu.getPid() != -1) {
			Menu resource = resourceIds.get(menu.getPid());
			resource.addChildMenu(menu);
			findMenu(resource, resourceIds);
			// 系统管理
			// 用户管理->系统管理
			// 用户查询->用户管理->系统管理
			
			
			
			
			
		}
	}

}
